/*
helferlein.com ( http://www.helferlein.com )
Michael Tobisch

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions 
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using DotNetNuke.Common.Utilities;
using helferlein.DNN.Modules.Form.Data;
using System.Text;

namespace helferlein.DNN.Modules.Form.Business
{
    /// -----------------------------------------------------------------------------
    ///<summary>
    /// The Controller class for the FormItem
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
   [DataObject]
   public class FormItemController
   {
#region Constructor
      public FormItemController()
      {
      }
#endregion

#region Public Methods
      /// <summary>
      /// Gets a FormItem from the database
      /// </summary>
      [DataObjectMethod(DataObjectMethodType.Select, true)]
      public FormItemInfo Get(int formItemID)
      {
         return CBO.FillObject<FormItemInfo>(DataProvider.Instance().GetFormItem(formItemID));
      }

      /// <summary>
      /// Gets all FormItems for a specific Module
      /// </summary>
      [DataObjectMethod(DataObjectMethodType.Select, false)]
      public List<FormItemInfo> GetAll(int moduleID)
      {
         return CBO.FillCollection<FormItemInfo>(DataProvider.Instance().GetFormItems(moduleID));
      }

      /// -----------------------------------------------------------------------------
      /// <summary>
      /// Adds a FormItem to the database
      /// </summary>
      /// -----------------------------------------------------------------------------
      [DataObjectMethod(DataObjectMethodType.Insert, true)]
// Code provided by User Lode_Leroy on CodePlex
//    public int Add(int portalID, int moduleID, FormItemType formItemType, int? formItemRepeatColumns, int? sortValue, bool formItemRequired, int? width, int? height, LinkTarget formItemLinkTarget, string validationExpression, Dictionary<string, string> aquarium)
      public int Add(int portalID, int moduleID, FormItemType formItemType, int? formItemRepeatColumns, int? sortValue, bool formItemRequired, bool formItemOther, int? width, int? height, LinkTarget formItemLinkTarget, string validationExpression, Dictionary<string, string> aquarium)
      {
         FormItemInfo fii = new FormItemInfo();
         fii.ModuleID = moduleID;
         fii.FormItemType = formItemType;
         fii.FormItemRepeatColumns = formItemRepeatColumns;
         fii.SortValue = sortValue;
         fii.FormItemRequired = formItemRequired;
         // <!-- Code provided by User Lode_Leroy on CodePlex
         fii.FormItemOther = formItemOther;
         // Code provided by User Lode_Leroy on CodePlex -->
         fii.Width = width;
         fii.Height = height;
         fii.FormItemLinkTarget = formItemLinkTarget;
         fii.ValidationExpression = validationExpression;
         return this.Add(fii, aquarium);
      }

      [DataObjectMethod(DataObjectMethodType.Insert, false)]
      public int Add(FormItemInfo fii, Dictionary<string, string> aquarium)
      {
         if (fii.SortValue == null)
            fii.SortValue = GetNewSortValue(fii.ModuleID);

         StringBuilder aquariumXML = new StringBuilder();
         aquariumXML.Append("<Aquarium>");
         foreach(KeyValuePair<string, string> babelFish in aquarium)
         {
            string[] keyLocale = babelFish.Key.ToString().Split('.');
            if (!(String.IsNullOrEmpty(babelFish.Value)))
            {
               aquariumXML.Append("<BabelFish>");
               aquariumXML.Append("<PortalID>[PORTAL_ID]</PortalID>");
               aquariumXML.Append("<Locale>");
               aquariumXML.Append(keyLocale[1]);
               aquariumXML.Append("</Locale>");
               aquariumXML.Append("<Qualifier>helferlein.Form.FormItem.[FORM_ITEM_ID]</Qualifier>");
               aquariumXML.Append("<StringKey>");
               aquariumXML.Append(keyLocale[0]);
               aquariumXML.Append("</StringKey>");
               aquariumXML.Append("<StringText><![CDATA[");
               aquariumXML.Append(babelFish.Value);
               aquariumXML.Append("]]></StringText>");
               aquariumXML.Append("</BabelFish>");
            }
         }
         aquariumXML.Append("</Aquarium>");
         return Convert.ToInt32(DataProvider.Instance().AddFormItem(fii.ModuleID, Convert.ToInt32(fii.FormItemType), fii.FormItemRepeatColumns, fii.SortValue.Value, fii.FormItemRequired, fii.FormItemOther, fii.Width, fii.Height, GetLinkTargetNull(fii.FormItemType, fii.FormItemLinkTarget), fii.ValidationExpression, aquariumXML.ToString()));
      }



      /// -----------------------------------------------------------------------------
      /// <summary>
      /// Updates a form item
      /// </summary>
      /// -----------------------------------------------------------------------------
      [DataObjectMethod(DataObjectMethodType.Update, true)]
// Code provided by User Lode_Leroy on CodePlex
//    public void Change(int moduleID, int formItemID, FormItemType formItemType, int? formItemRepeatColumns, int sortOrder, bool formItemRequired, bool formItemOther, int? width, int? height, LinkTarget formItemLinkTarget, string validationExpression, Dictionary<string, string> aquarium)
      public void Change(int moduleID, int formItemID, FormItemType formItemType, int? formItemRepeatColumns, int sortOrder, bool formItemRequired, bool formItemOther, int? width, int? height, LinkTarget formItemLinkTarget, string validationExpression, Dictionary<string, string> aquarium)
      {
         FormItemInfo fii = new FormItemInfo();
         fii.ModuleID = moduleID;
         fii.FormItemID = formItemID;
         fii.FormItemType = formItemType;
         fii.FormItemRepeatColumns = formItemRepeatColumns;
         fii.SortValue = sortOrder;
         fii.FormItemRequired = formItemRequired;
         // <!-- Code provided by User Lode_Leroy on CodePlex
         fii.FormItemOther = formItemOther;
         // Code provided by User Lode_Leroy on CodePlex -->
         fii.Width = width;
         fii.Height = height;
         fii.FormItemLinkTarget = formItemLinkTarget;
         fii.ValidationExpression = validationExpression;
         this.Change(fii, aquarium);
      }

      /// -----------------------------------------------------------------------------
      /// <summary>
      /// Updates a form item
      /// </summary>
      /// -----------------------------------------------------------------------------
      [DataObjectMethod(DataObjectMethodType.Update, false)]
      public void Change(FormItemInfo fii, Dictionary<string, string> aquarium)
      {
         StringBuilder aquariumXML = new StringBuilder();
         aquariumXML.Append("<Aquarium>");
         foreach (KeyValuePair<string, string> babelFish in aquarium)
         {
            string[] keyLocale = babelFish.Key.ToString().Split('.');
            if (!(String.IsNullOrEmpty(babelFish.Value)))
            {
               aquariumXML.Append("<BabelFish>");
               aquariumXML.Append("<PortalID>");
               aquariumXML.Append(fii.PortalID);
               aquariumXML.Append("</PortalID>");
               aquariumXML.Append("<Locale>");
               aquariumXML.Append(keyLocale[1]);
               aquariumXML.Append("</Locale>");
               aquariumXML.Append("<Qualifier>");
               aquariumXML.Append(String.Format("helferlein.Form.FormItem.{0}", fii.FormItemID));
               aquariumXML.Append("</Qualifier>");
               aquariumXML.Append("<StringKey>");
               aquariumXML.Append(keyLocale[0]);
               aquariumXML.Append("</StringKey>");
               aquariumXML.Append("<StringText><![CDATA[");
               aquariumXML.Append(babelFish.Value);
               aquariumXML.Append("]]></StringText>");
               aquariumXML.Append("</BabelFish>");
            }
            else
            {
               new helferlein.DNN.Modules.BabelFish.Business.BabelFishController().Drop(fii.PortalID, keyLocale[1], String.Format("helferlein.Form.FormItem.{0}", fii.FormItemID), keyLocale[0]);
            }
         }
         aquariumXML.Append("</Aquarium>");
         // Code provided by User Lode_Leroy on CodePlex
         // DataProvider.Instance().UpdateFormItem(fii.ModuleID, fii.FormItemID, Convert.ToInt32(fii.FormItemType), fii.FormItemRepeatColumns, fii.SortValue.Value, fii.FormItemRequired, fii.Width, fii.Height, GetLinkTargetNull(fii.FormItemType, fii.FormItemLinkTarget), fii.ValidationExpression, aquariumXML.ToString());
         DataProvider.Instance().UpdateFormItem(fii.ModuleID, fii.FormItemID, Convert.ToInt32(fii.FormItemType), fii.FormItemRepeatColumns, fii.SortValue.Value, fii.FormItemRequired, fii.FormItemOther, fii.Width, fii.Height, GetLinkTargetNull(fii.FormItemType, fii.FormItemLinkTarget), fii.ValidationExpression, aquariumXML.ToString());
      }

      /// -----------------------------------------------------------------------------
      /// <summary>
      /// Deletes a form item
      /// </summary>
      /// -----------------------------------------------------------------------------
      [DataObjectMethod(DataObjectMethodType.Delete, true)]
      public void Drop(int formItemID)
      {
         DataProvider.Instance().DeleteFormItem(formItemID);
      }

      public void RequireItem(int formItemID)
      {
         DataProvider.Instance().RequireItem(formItemID);
      }

      public void MoveTop(int formItemID)
      {
         DataProvider.Instance().MoveTop(formItemID);
      }

      public void MoveBottom(int formItemID)
      {
         DataProvider.Instance().MoveBottom(formItemID);
      }

      public void Move(int formItemID, int direction)
      {
         DataProvider.Instance().Move(formItemID, direction);
      }
#endregion

#region Private Methods
      /// <summary>
      /// Gets a new sort value
      /// </summary>
      /// <param name="portalID">ID of the DotNetNuke Portal</param>
      /// <param name="moduleID">ID of the module</param>
      /// <returns>Integer - the new sort value</returns>
      private int GetNewSortValue(int moduleID)
      {
         return (DataProvider.Instance().GetNextSortValue(moduleID));
      }

      /// <summary>
      /// Gets an integer representing the link target
      /// </summary>
      /// <param name="formItemType">Type of the form item</param>
      /// <param name="linkTarget">Target for the item</param>
      /// <returns>int? result</returns>
      private int? GetLinkTargetNull(FormItemType formItemType, LinkTarget? linkTarget)
      {
         int? result = null;
         if (formItemType == FormItemType.WebSite)
         {
            if ((linkTarget != null) && (linkTarget != LinkTarget.None))
               result = (int)linkTarget;
         }
         return result;
      }
#endregion
   }
}